#!/bin/sh /etc/rc.common
# Copyright (C) 2019, Anton Kikin, <a.kikin@tano-systems.com>

START=00
STOP=99
USE_PROCD=1

WATCHDOG_BIN=/sbin/watchdog

validate_procd_section()
{
	uci_validate_section watchdog procd "${1}" \
		'timeout:uinteger:30' \
		'frequency:uinteger:5'
}

validate_watchdog_section()
{
	uci_validate_section watchdog watchdog "${1}" \
		'device:string:/dev/watchdog' \
		'timeout:uinteger:30' \
		'frequency:uinteger:5' \
		'policy:string' \
		'priority:uinteger' \
		'nice:integer'
}

procd_watchdog_stop() {
	ubus call system watchdog "{'stop':true,'magicclose':true}" > /dev/null 2>&1
}

procd_watchdog_start() {
	ubus call system watchdog "{'stop':false,'timeout':30,'frequency':5}" > /dev/null 2>&1
}

watchdog_config() {
	local cfg="${1}"

	local keep_procd
	local device
	local timeout
	local frequency
	local policy
	local priority
	local nice

	[ -x "${WATCHDOG_BIN}" ] || return

	validate_watchdog_section "${cfg}" || {
		echo "Validation failed"
		return 1
	}

	procd_open_instance

	procd_set_param command ${WATCHDOG_BIN} -t ${frequency} -T ${timeout}
	procd_append_param command -F
	procd_append_param command ${device}
	procd_set_param respawn
	procd_set_param stderr 1
	procd_set_param stdout 1

	if [ "${policy}" == "SCHED_FIFO" ] || [ "${policy}" == "SCHED_RR" ]; then
		[ -n "${priority}" ] || priority=1
	fi

	[ -n "${policy}" ] && procd_set_param policy "${policy}"
	[ -n "${priority}" ] && procd_set_param priority ${priority}
	[ -n "${nice}" ] && procd_set_param nice ${nice}

	procd_close_instance
}

service_triggers() {
	procd_add_reload_trigger "watchdog"
	procd_add_validation validate_watchdog_section
	procd_add_validation validate_procd_section
}

stop_service() {
	:
	# Start procd watchdog
	# procd_watchdog_start
}

start_service() {
	# Stop procd watchdog
	procd_watchdog_stop

	# Configure external watchdog
	config_load watchdog
	config_foreach watchdog_config watchdog
}
